package org.example.controller;

import org.example.domain.Comment;
import org.example.response.ApiResponse;
import org.example.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@RestController
@RequestMapping("/api/comments")
@Slf4j
public class CommentController {

    @Autowired
    private CommentService commentService;

    /***
     * 创建评论
     * @param comment
     * @return
     */
    @PostMapping("/create")
    public ApiResponse<Comment> createComment(@RequestBody Comment comment) {
        try {
            return ApiResponse.success(commentService.createComment(comment));
        } catch (Exception e) {
            return ApiResponse.error(500, "创建评论失败: " + e.getMessage());
        }
    }

    /***
     * 获取帖子的所有评论
     * @param postId
     * @return
     */
    @GetMapping("/post/{postId}")
    public ApiResponse<List<Comment>> getPostComments(@PathVariable String postId) {
        try {
            return ApiResponse.success(commentService.getPostComments(postId));
        } catch (Exception e) {
            return ApiResponse.error(500, "获取评论失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取评论的直接回复
     * @param commentId 评论ID
     * @return 回复列表
     */
    @GetMapping("/{commentId}/replies")
    public ApiResponse<List<Comment>> getCommentReplies(@PathVariable String commentId) {
        try {
            List<Comment> replies = commentService.getCommentReplies(commentId);
            return ApiResponse.success(replies);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取回复失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定帖子下某条评论的所有子评论
     * @param postId 帖子ID
     * @param commentId 评论ID
     * @return 子评论列表
     */
    @GetMapping("/lower/{postId}/{commentId}")
    public ApiResponse<List<Comment>> getLowerComments(
            @PathVariable String postId,
            @PathVariable String commentId) {
        try {
            List<Comment> lowerComments = commentService.getLowerComments(postId, commentId);
            return ApiResponse.success(lowerComments);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取子评论失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定帖子下特定评论的所有回复
     * @param postId 帖子ID
     * @param commentId 评论ID
     * @return 评论回复列表
     */
    @GetMapping("/post/{postId}/{commentId}")
    public ApiResponse<List<Comment>> getPostCommentReplies(@PathVariable String postId, @PathVariable String commentId) {
        try {
            List<Comment> replies = commentService.getPostCommentReplies(postId, commentId);
            return ApiResponse.success(replies);
        } catch (Exception e) {
            log.error("获取评论回复失败: postId={}, commentId={}", postId, commentId, e);
            return ApiResponse.error(500, "获取评论回复失败");
        }
    }
}